package com.studyinghome.exception;

import com.studyinghome.result.CodeMsg;
import com.studyinghome.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author leslie
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            log.error(ex.getMessage());
            return Result.error(CodeMsg.SERVER_ERROR);
        } else if (e instanceof BindException) {
            log.error(e.toString());
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        } else if (e instanceof IllegalArgumentException) {
            return Result.error(CodeMsg.DATA_TYPE_ERROR);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return Result.error(CodeMsg.REQUEST_METHOD_NOT_SUPPORTED);
        } else if (e instanceof NullPointerException) {
            log.error("空指针异常：" + e);
            return Result.error(CodeMsg.SERVER_ERROR);
        } else if (e instanceof NumberFormatException) {
            log.error("数据转换异常：" + e);
            return Result.error(CodeMsg.SERVER_ERROR);
        } else if (e instanceof ClassCastException) {
            log.error("类型转换异常：" + e);
            return Result.error(CodeMsg.SERVER_ERROR);
        } else {
            log.error("未知异常：" + e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
